package logic

import (
	"context"
	"errors"
	"storage/common"

	"storage/internal/svc"
	"storage/pb/storage"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetFileListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetFileListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFileListLogic {
	return &GetFileListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// GetFileList 获取文件列表
func (l *GetFileListLogic) GetFileList(in *storage.FileListRequest) (*storage.FileListResponse, error) {
	var orderByStr string
	orderByStr, ok := common.FileOrderMap[int(in.OrderBy)]
	if !ok {
		return nil, errors.New("orderBy参数错误")
	}
	files, total, lastId, err := l.svcCtx.StorageModel.GetFileList(l.ctx, in.UserId, in.ParentId, in.FileType, in.Status, in.LastId, in.Limit, in.Keyword, in.FileExt, orderByStr)
	if err != nil {
		return nil, err
	}

	var list []*storage.FileInfo
	for _, file := range files {
		list = append(list, &storage.FileInfo{
			Id:       file.Id,
			UserId:   file.UserId,
			ParentId: file.ParentId,
			FileName: file.FileName,
			FileHash: file.FileHash,
			FileSize: file.FileSize,
			FileType: file.FileType,
			Status:   file.Status,
			CreateAt: file.CreateAt.Unix(),
			UpdateAt: file.UpdateAt.Unix(),
		})
	}
	return &storage.FileListResponse{Total: total, LastId: lastId, List: list}, nil
}
